# app.py - Flask后端
from flask import Flask, render_template, request, jsonify
import socket

app = Flask(__name__)

# 设备指令映射表（示例，需要根据实际协议修改）
COMMANDS = {
    "living_room_light": {
        "on": bytes([0x09, 0x08, 0x01, 0x01, 0x08, 0x09]),
        "off": bytes([0x09, 0x08, 0x01, 0x00, 0x08, 0x09])
    },
    "second_floor_light": {
        "on": bytes([0x09, 0x08, 0x02, 0x01, 0x08, 0x09]),
        "off": bytes([0x09, 0x08, 0x02, 0x00, 0x08, 0x09])
    },
    "fan": {
        "on": bytes([0x09, 0x08, 0x03, 0x01, 0x08, 0x09]),
        "off": bytes([0x09, 0x08, 0x03, 0x00, 0x08, 0x09])
    },
    "face_recognition": {
        "on": bytes([0x09, 0x08, 0x04, 0x01, 0x08, 0x09]),
        "off": bytes([0x09, 0x08, 0x04, 0x00, 0x08, 0x09])
    }
}

# 设备服务器配置（示例）
DEVICE_SERVER = ('192.168.239.77', 9898)


def send_command(command):
    """通过Socket发送指令"""
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect(DEVICE_SERVER)
            s.sendall(command)
            return True
    except Exception as e:
        print(f"Error sending command: {e}")
        return False


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/control', methods=['POST'])
def control():
    device = request.json.get('device')
    action = request.json.get('action')

    if device not in COMMANDS or action not in ['on', 'off']:
        return jsonify(success=False)

    command = COMMANDS[device][action]
    if send_command(command):
        return jsonify(success=True)
    return jsonify(success=False)


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8080,debug=True)